package com.kitten.dataAlign.job;

import com.kitten.dataAlign.domain.mapper.DeleteTableMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author kitten
 */
@Slf4j
@Component
@RefreshScope
public class DeleteTableXxlJob {

    @Value("${table.shards}")
    private int tableShards;

    @Resource
    private DeleteTableMapper deleteTableMapper;

    @XxlJob("DeleteTableJobHandler")
    public void deleteTableJobHandler() throws Exception{
        XxlJobHelper.log("##    开始删除最近一周的增量表数据");

        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        LocalDate startDate = today;
        LocalDate endDate = today.minusWeeks(1);

        while (startDate.isAfter(endDate)) {    //
            startDate = startDate.minusDays(1);

            for(int i = 0; i < tableShards; i++) {
                String tableNameSuffix = startDate.format(formatter);

                // 删除表
                deleteTableMapper.deleteDataAlignFollowingCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignFansCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignNoteLikeCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignNoteCollectCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignUserLikeCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignUserCollectCountTempTable(tableNameSuffix);
                deleteTableMapper.deleteDataAlignUserPublishNoteCountTempTable(tableNameSuffix);
            }
        }

        log.info("删除最近一周的 {} 片日增量表数据", tableShards);
    }

}
